<?php
/**
 * Created by PhpStorm.
 * User: palidin
 * Date: 2018/8/23
 * Time: 9:54
 */

namespace App\Http\Middleware;


use Fresh\Annotation\AuthorizationIgnored;
use Fresh\Annotation\Authorize;
use Fresh\Foundation\Dispatcher;
use Fresh\Foundation\Dispatcher\Route;
use Fresh\Foundation\Exception\UnauthorizedException;
use Fresh\Mvc\Middleware;

/**
 * @Annotation
 * @Target("ALL")
 */
class AuthMiddleware extends Middleware
{
    private function isNeedAuthorize($className, $methodName)
    {
        $meta = $this->getDI()->getClassMetaManager();
        $classInclude = $meta->getClassAnnotation($className, Authorize::class);
        $methodInclude = $meta->getMethodAnnotation($className, $methodName, Authorize::class);
        $methodIgnore = $meta->getMethodAnnotation($className, $methodName, AuthorizationIgnored::class);

        return $methodInclude || (!$methodIgnore && $classInclude);
    }

    public function handle(Dispatcher $dispatcher, Route $route)
    {
        if ($this->isNeedAuthorize($route->getControllerName(), $route->getActionName())) {
            if (!$dispatcher->getDI()->getSession()->getUserId()) {
                throw new UnauthorizedException();
            }
        }
        return true;
    }

}